const {
	ObjectID,
} = require('mongodb')
const Response = require('./Response')
const {
	userColPromise,
	projectColPromise,
	userProjectColPromise,
	userHistoryColPromise,
} = require('../dbs/db-mongo')
const {
	uploadFiles,
} = require('../utils')
const {
	getTime,
	getWeekIndex,
} = require('../utils/dateUtils')

module.exports = {

	/**
	 * 项目列表
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	listProject: async function(params) {
		let {
			page,
			num,
		} = params
		page = Number(page) || 1
		num = Number(num) || 10
		let projectCol = await projectColPromise
		let total = await projectCol.count();
		let docs = await projectCol.find({}, {
			name: 1,
			img_url: 1,
			start_time: 1,
			end_time: 1,
			desc: 1,
			create_time: 1,
			modify_time: 1,
		}).sort({
			create_time: -1,
		}).skip((page - 1) * num).limit(num).toArray();
		return new Response('000', '成功', {
			docs,
			total,
		})
	},

	/**
	 * 项目详情
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	detailProject: async function(params) {
		let {
			id,
		} = params
		if (!id)
			return new Response('101', '请求参数错误')
		let projectCol = await projectColPromise
		let result = await projectCol.findOne({
			_id: ObjectID(id),
		})
		return new Response('000', '成功', result)
	},

	/**
	 * 项目报名
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	userApplyProject: async function(req) {
		let project_id = req.body.project_id
		if (!project_id)
			return new Response('101', '请求参数错误')
		let {
			_uid: uid,
			_userInfo: userInfo,
		} = req.session
		let userProjectCol = await userProjectColPromise
		let result = await userProjectCol.findOne({
			uid,
			project_id
		})
		if (result && result._id)
			return new Response('200', '已报名')
		let projectCol = await projectColPromise
		result = await projectCol.findOne({
			_id: ObjectID(project_id)
		})
		if (!result)
			return new Response('205', '项目不存在')
		if (new Date(result.start_time) > new Date())
			return new Response('301', '报名未开始')
		if (new Date(result.end_time) < new Date())
			return new Response('302', '报名已结束')
		result = await userProjectCol.insertOne({
			project_id,
			uid,
			nickname: req.session._userInfo.nickname,
			week_submit: 0,
			total_submit: 0,
			grade: -1,
			create_time: getTime(),
			modify_time: getTime(),
		})
		if (!result || !result.insertedId)
			return new Response('201', '报名失败', result)
		let projectSet = new Set(userInfo.projects)
		projectSet.add(project_id)
		let projects = Array.from(projectSet)
		let userCol = await userColPromise
		result = await userCol.updateOne({
			_id: userInfo._id
		}, {
			$set: {
				projects,
			}
		})
		userInfo.projects = projects
		return new Response('000', '成功', userInfo)
	},

	/**
	 * 项目排行
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	rankProject: async function(params) {
		let {
			project_id,
		} = params
		if (!project_id)
			return new Response('101', '请求参数错误')
		let userProjectCol = await userProjectColPromise
		let result = await userProjectCol.find({
			project_id,
			grade: {
				$gt: -1,
			}
		}).sort({
			grade: -1,
		}).limit(40).toArray()
		return new Response('000', '成功', {
			docs: result
		})
	},

	/**
	 * 上传结果
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	uploadResult: async function(req) {
		let project_id = req.query.project_id;
		if (!project_id)
			return new Response('101', '请求参数错误')
		let uid = req.session._uid;
		let userInfo = req.session._userInfo
		// 参与项目信息
		let userProjectCol = await userProjectColPromise
		let result = await userProjectCol.findOne({
			uid,
			project_id,
		})
		if (!result || !result._id)
			return new Response('205', '还未报名')
		let {
			week_submit,
			modify_time,
			total_submit,
			grade,
		} = result;
		// 最后一次提交时间不是本周，重置提交次数
		week_submit = getWeekIndex() != getWeekIndex(modify_time) ? 0 : week_submit
		if (week_submit >= 3)
			return new Response('303', '本周已上传了3次，请下周再试')
		week_submit += 1
		total_submit += 1
		let {
			files,
			fileName,
			url,
		} = await uploadFiles(req, {
			destDir: `result/${project_id}/${uid}`,
			fileName: getTime().replace(/\s/g, '_'),
		})
		userProjectCol.findOneAndUpdate({
			_id: result._id
		}, {
			$set: {
				nickname: userInfo.nickname,
				week_submit,
				total_submit,
				modify_time: getTime(),
			}
		});
		// 记录用户提交历史
		let userHistoryCol = await userHistoryColPromise
		result = await userHistoryCol.insertOne({
			project_id,
			uid,
			nickname: userInfo.nickname,
			total_submit,
			grade: -1,
			rank: -1,
			url,
			create_time: getTime(),
			modify_time: getTime(),
		})
		if (!result || !result.insertedId)
			return new Response('201', '上传失败', result)
		return new Response('000', '成功', {
			success: 'success'
		})
	},
}

/**
 * 计算成绩
 * @return {[type]} [description]
 */
// function parseResultGrade() {
// 	return new Promise((resolve, reject) => {
// 		resolve(Number(Math.random().toFixed(6)))
// 	});
// }